<template>
	<div class="goods-list" v-loading="loading" @scroll="handleScroll">
		<div v-for="item in goodsList" :key="item.id" class="item">
			<img src="@/assets/1.jpg" alt="" class="img">
			<div class="info">
				<div class="name">{{ item.name }}</div>
				<div class="price">
					<span><i class="iconfont icon-jiage"></i>{{ item.price }}</span>
					<span><i class="iconfont icon-shoucang"></i>{{ item.collction }}</span>
				</div>
			</div>
		</div>
		<div class="no-data">{{ isHave ? '加载中...' : '没有更多了' }}</div>
	</div>
</template>
<script setup>
import { getUserList } from '@/api/index';
import mitt from '@/utils/bus';
import { debounce } from 'lodash-es'
const loading = ref(false);
const goodsList = ref([]); // 商品列表
const isHave = ref(true); // 是否还有数据
const searchParams = reactive({
	pageNo: 1,
	pageSize: 10,
	searchKey: ''
})

onMounted(() => {
	getList();
})

// 商品列表
const getList = async () => {
	// 如果是第一页且列表不为空，说明是搜索操作，不需要显示loading
	if (searchParams.pageNo !== 1 || goodsList.value.length === 0) {
		loading.value = true;
	}

	let timer = setTimeout(async () => {
		clearTimeout(timer);
		const res = await getUserList(searchParams);
		loading.value = false;

		if (res.data?.list.length < searchParams.pageSize) {
			isHave.value = false;
		}

		// 如果是第一页，替换数据；否则追加数据
		goodsList.value = searchParams.pageNo === 1
			? res.data?.list || []
			: [...goodsList.value, ...(res.data?.list || [])];

	}, 100)
}

// 触底加载
const handleScroll = debounce(() => {
	const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
	const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
	const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
	if (scrollTop + clientHeight >= scrollHeight - 100 && isHave.value) {
		searchParams.pageNo++;
		getList();
	}
}, 300)

mitt.on('search', (val) => {
	searchParams.pageNo = 1;
	goodsList.value = [];
	searchParams.searchKey = val;
	isHave.value = true;
	getList();
})

</script>
<style lang="scss" scoped>
.goods-list {
	padding: 10px;
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	row-gap: 20px;
	height: calc(100vh - 80px);
	overflow-y: scroll;

	.item {
		width: calc((100% - 10px) / 2);

		.img {
			width: 100%;
		}

		.info {
			.name {
				font-weight: 600;
				padding: 4px 0;
			}

			.price {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			span {
				display: flex;
				align-items: center;
			}
		}
	}

	.no-data {
		display: inline-flex;
		width: 100%;
		justify-content: center;
		padding: 10px 0;
		color: #999;
	}
}
</style>
